﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Diagnostics;
using Hotkey;
using System.Windows.Interop;
using System.Windows.Automation;
using System.Windows.Automation.Text;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Speech.Synthesis;

namespace EasyRead
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        NotifyIcon _ico;

        public MainWindow()
        {
            _ico = new NotifyIcon();
            _ico.BalloonTipTitle = "EasyRead Text Reader";
            _ico.BalloonTipText = "EasyRead is still running, it has just been minimized. Double click to restore to normal size";
            _ico.Text = "EasyRead Text Reader";

            _ico.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(ico_MouseDoubleClick);
            _ico.MouseClick += new System.Windows.Forms.MouseEventHandler(ico_MouseClick);

            try
            {
                _ico.Icon = new System.Drawing.Icon("Resources\\book.ico");
            }
            catch(Exception e)
            {
                Debug.Print(e.StackTrace);
            }

            InitializeComponent();
            
        }

        private void ico_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            WindowInSysTray(false);
        }

        private void ico_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                try
                {
                    SysTrayContextMenu.IsOpen = true;
                }
                catch (Exception ex)
                {
                    Debug.Print(ex.StackTrace);
                }
                
            }
        }
        
        private void MainWindow_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                WindowInSysTray(true);
            }
            else
            {
                WindowInSysTray(false);
            }
        }

        private void WindowInSysTray(bool inTray)
        {
            if (inTray)
            {
                this.ShowInTaskbar = false;
                this.WindowState = WindowState.Minimized;

                if (_ico != null)
                {
                    _ico.Visible = true;
                }
            }
            else
            {
                this.ShowInTaskbar = true;
                this.WindowState = WindowState.Normal;
                this.Activate();
                if (_ico != null)
                {
                    _ico.Visible = false;
                }
            }
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            WindowInSysTray(true);
            Hotkey.Win32.UnhookWindowsHookEx(Hotkey.Win32._hookID);
            Hotkey.Win32.StopTimer();

            //if (atom != 0)
            //{
            //    Win32.UnregisterHotKey(hWndSource.Handle, atom);
            //}
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Hotkey.Win32.SetHook();

            Hotkey.Win32.HookInvoked += new Hotkey.Win32.HookEventHandler(PopText);
        }

        private void PopText(object sender, Hotkey.HookEventArgs e)
        {
            SpeechSynthesizer synth = new SpeechSynthesizer();
            synth.Speak((string)sender);
        }

        private IntPtr MainWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            //switch (msg)
            //{
            //    case Win32.WM_HOTKEY:
            //        CaptureSelection();
            //        handled = true;
            //        break;
            //}

            return IntPtr.Zero;
        }

        private void CaptureSelection()
        {
            try
            {
                //var builder = new StringBuilder(500);
                //int foregroundWindowHandle = Win32.GetForegroundWindow();
                //uint remoteThreadId = Win32.GetWindowThreadProcessId(foregroundWindowHandle, 0);
                //uint currentThreadId = Win32.GetCurrentThreadId();

                //Win32.AttachThreadInput(remoteThreadId, currentThreadId, true);
                //IntPtr activeCtrlId = Win32.GetFocus();

                ////Win32.SendMessage(activeCtrlId, Win32.WM_GETTEXT, builder.Capacity, builder);
                ////var text = builder.ToString();
                //var text = GetText(activeCtrlId);

                //System.Windows.MessageBox.Show(text);
                //AutomationElement element = AutomationElement.FocusedElement;

                //if (element != null)
                //{
                //    System.Windows.MessageBox.Show(element.Current.Name + "\n" + element.Current.ControlType + "\n" + element.Current.ClassName + "\n"
                //        + element.Current.NativeWindowHandle);
                //    TextPattern tp = element.GetCurrentPattern(TextPattern.Pattern) as TextPattern;

                //    System.Windows.MessageBox.Show(tp.SupportedTextSelection.ToString());
                //    StringBuilder sb = new StringBuilder();

                //    foreach (TextPatternRange r in tp.GetSelection())
                //    {
                //        sb.AppendLine(r.GetText(-1));
                //    }

                //    tbContent.Text = string.Format("Go selected text:\r\n{0}",
                //                                    sb.ToString(),
                //                                    sb.Length);
                //}
            }
            catch (Exception e)
            {
                tbContent.Text = string.Format("Failed to capture selection.\r\n\r\n{0}", e);
            }
        }

        private string GetText(IntPtr handle)
        {
            int maxLength = 512;
            IntPtr buffer = Marshal.AllocHGlobal((maxLength + 1) * 2);
            string w = Marshal.PtrToStringAuto(buffer);

            Marshal.FreeHGlobal(buffer);
            return w;
        }
    }
}
